<template>
  <div>
    <el-input></el-input>
    <el-tree
      style="margin: 20px 0"
      ref="treeRef"
      :data="allPermissions"
      node-key="id"
      show-checkbox
      default-expand-all
      :props="defaultProps"
    >
    </el-tree>
    <el-button @click="save">保存</el-button>
    <el-button @click="cancel">取消</el-button>
  </div>
</template>
<script>
import { reqAssignRoleList, reqAssignRole } from "@/api/acl/role";
import { async } from "q";
export default {
  name: "roleAuth",
  data() {
    return {
      roleId: this.$route.query.id, //当前角色id
      allPermissions: [], //权限列表
      defaultProps: {
        children: "children",
        label: "name"
      },
      checkedIds: [] //选中的项的id组成的数组
    };
  },
  methods: {
    // 1.获取所有的权限列表
    getPermissions(roleId) {
      reqAssignRoleList(roleId).then(res => {
        // console.log(res, "888");
        this.allPermissions = res.children;
        this.checkedIds = this.getCheckedIds(this.allPermissions);
        // 通过 keys 设置目前勾选的节点
        this.$refs.treeRef.setCheckedKeys(this.checkedIds);
      });
    },
    // 2.得到所有全选的项的id的列表
    getCheckedIds(auths, initArr = []) {
      auths.forEach(item => {
        // 如果当前元素选中并且他的层级为4(只有4层),那就把他的id收集到数组中去
        if (item.select && item.level === 4) {
          initArr.push(item.id);
          //   否则,如果还存在children的话,递归调用
        } else if (item.children) {
          this.getCheckedIds(item.children, initArr);
        }
      });
      return initArr;
    },
    save() {
      // 得到所有全选的id
      this.checkedIds = this.$refs.treeRef.getCheckedKeys();
      //   console.log( this.checkedIds)
      // 得到所有半选的id
      const halfCheckedIds = this.$refs.treeRef.getHalfCheckedKeys();
      // 合并全选和半选的id， 并用逗号连接成串
      var ids = this.checkedIds?.concat(halfCheckedIds).join(",");
      reqAssignRole(this.roleId, ids).then(async () => {
        this.$message.success("分配权限成功");
        // 跳转到角色列表页面
        await this.$router.replace("/acl/role/list");
      });
    },
    cancel() {
      // 跳转到角色列表
      this.$router.replace("/acl/role/list");
    }
  },

  mounted() {
    this.getPermissions(this.roleId);
  }
};
</script>
